﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

[RequireComponent (typeof(UIGrid))]
public class ImageGridController : MonoBehaviour 
{
    public UIDraggablePanel draggablePanel;
    public GameObject newCell;
    public AppController appController;

    public UITexture image1;
    public UITexture image2;
    public UITexture image3;

    public Material defaultImage;

    public LeftButton leftButton;
    public RightButton rightButton;

    bool leftButtonTap = false;
    bool rightButtonTap = false;

    public bool posChanged = false;
    int currentImageNumber = 0;

    void OnLeftButtonClick()
    {
        leftButtonTap = true;
    }
    void OnRightButtonClick()
    {
        rightButtonTap = true;
    }
    void Start()
    {
        leftButton.ClickEvent -= OnLeftButtonClick;
        leftButton.ClickEvent += OnLeftButtonClick;

        rightButton.ClickEvent -= OnRightButtonClick;
        rightButton.ClickEvent += OnRightButtonClick;
    }

    void Update()
    {
        //Переключение между фотография при помощи tap


        if (rightButtonTap == true)
        {
            currentImageNumber++;

            if (!LoadImage(ref image1, currentImageNumber - 1))
                LoadDefaultImage(ref image1);
            if (!LoadImage(ref image2, currentImageNumber))
                LoadDefaultImage(ref image2);
            if (!LoadImage(ref image3, currentImageNumber + 1))
                LoadDefaultImage(ref image3);

            Resources.UnloadUnusedAssets();
            
            rightButtonTap = false;
            return;
        }

        if (leftButtonTap == true)
        {
            currentImageNumber--;

            if (!LoadImage(ref image1, currentImageNumber - 1))
                LoadDefaultImage(ref image1);
            if (!LoadImage(ref image2, currentImageNumber))
                LoadDefaultImage(ref image2);
            if (!LoadImage(ref image3, currentImageNumber + 1))
                LoadDefaultImage(ref image3);

            Resources.UnloadUnusedAssets();
 
            leftButtonTap = false;
            return;
        }



        //Переключение между фотография при помощи slide
        /*
        if (draggablePanel.GetComponent<UIPanel>().clipRange.x >= 1100f)
        {
            Vector4 v4 = draggablePanel.GetComponent<UIPanel>().clipRange;
            v4.x = 0;
            draggablePanel.GetComponent<UIPanel>().gameObject.transform.localPosition = new Vector3(0f, 0f, 0f);
            draggablePanel.GetComponent<UIPanel>().clipRange = v4;
            currentImageNumber++;
            posChanged = true;
        }
        if (draggablePanel.GetComponent<UIPanel>().clipRange.x <= -1100f)
        {
            Vector4 v4 = draggablePanel.GetComponent<UIPanel>().clipRange;
            v4.x = 0;
            draggablePanel.GetComponent<UIPanel>().gameObject.transform.localPosition = new Vector3(0f, 0f, 0f);
            draggablePanel.GetComponent<UIPanel>().clipRange = v4;
            currentImageNumber--;
            posChanged = true;
        }

        if (posChanged)
        {
            Debug.Log("Memory usage: " + GC.GetTotalMemory(false) / 1024);
            if (!LoadImage(ref image1, currentImageNumber - 1))
                LoadDefaultImage(ref image1);
            if (!LoadImage(ref image2, currentImageNumber))
                LoadDefaultImage(ref image2);
            if (!LoadImage(ref image3, currentImageNumber + 1))
                LoadDefaultImage(ref image3);
            posChanged = false;
            Debug.Log("Memory usage: " + GC.GetTotalMemory(false) / 1024);
            Resources.UnloadUnusedAssets();
        }
        */
    }

    bool LoadImage(ref UITexture image, int number)
    {
        /*
        Здесь добавить проверку на наличие картин    
        */
       
        number = number % (appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).images.Count;
        if (number < 0)
            number = (appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).images.Count + number;
        

        if ((appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).imagesDone[number] == false)
            return false;

        Shader shader = Shader.Find("Unlit/Texture");
        Material mat = new Material(shader);
        mat.name = "Picture from Artscroll";
        
        Texture2D tmpTexture = new Texture2D((appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).images[number].width,
                                        (appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).images[number].height);
        tmpTexture.Compress(true);
        tmpTexture.LoadImage((appController.artistsListRaw[appController.selectedChar][appController.selectedArtist] as ArtistInfo).images[number].bytes);
        mat.mainTexture = tmpTexture;
        image.material = mat;
        image.gameObject.transform.localScale = new Vector3(1000f, 500f, 1f);
        return true;
    }

    void LoadDefaultImage(ref UITexture image)
    {
        image.material = defaultImage;        
    }
    

    //Старые функции
    public void AddCell(ArtistInfo artistInfo, int imageIndex)
    {
        Debug.Log("Image grid controller AddCell() start (" + imageIndex + ")");
        //Debug.Log("Artist name: " + artistInfo.artistName);
        GameObject cell = NGUITools.AddChild(gameObject, newCell);
        if (cell == null)
            Debug.Log("Grid cell is Null");

        Shader shader = Shader.Find("Unlit/Texture");
        Material mat = new Material(shader);
        mat.name = "Picture from Artscroll";

        mat.mainTexture = new Texture2D(1000, 1000, TextureFormat.RGB24, false);
        //ОБЯЗАТЕЛЬНО РАСКОМЕНТИРОВАТЬ - загрузка картины в материал
        //mat.mainTexture = artistInfo.images[imageIndex];
        cell.GetComponent<UITexture>().material = mat;
        
        cell.transform.localScale = new Vector3(1000f, 500f, 1f);
        int h = mat.mainTexture.height;
        int w = mat.mainTexture.width;
        //cell.GetComponent<UITexture>().MakePixelPerfect();
        /*
        float scaleFactorW = 1000 / w;
        float scaleFactorH = 600 / h;
        if ((scaleFactorH < 1) && (scaleFactorW < 1))
            cell.transform.localScale = new Vector3(w * System.Math.Min(scaleFactorW, scaleFactorH), h * System.Math.Min(scaleFactorW, scaleFactorH), 1f);
        */
        //gameObject.GetComponent<UIGrid>().Reposition();
        //Debug.Log("Image grid controller AddCell() end (" + imageIndex + ")");
    }
    public void RemoveAllCells()
    {
        //Debug.Log("RemoveAllCells() is start: " + gameObject.transform.childCount);
        while (gameObject.transform.childCount > 0)
        {
            gameObject.transform.GetChild(0).gameObject.SetActive(false);
            gameObject.transform.GetChild(0).gameObject.transform.parent = appController.recycleBin.transform;
        }
        gameObject.GetComponent<UIGrid>().repositionNow = true;
        /*
        if (gameObject.transform.childCount != 0)
            Debug.Log("RemoveAllCells() is FAILED: " + gameObject.transform.childCount);
        else
            Debug.Log("RemoveAllCells() is SUCCEED");
        */
    }

}
